package com.c.ctgproject.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.c.ctgproject.R
import com.c.ctgproject.receiver.MyBroadcastReceiver
import com.c.ctgproject.utils.MyConstants
import com.c.ctgproject.utils.MyLog


/**
 *作者:LiBW
 *创建日期: 2020/8/31
 *描述:App保活Service
 */
class ResidentService : Service() {
    private val noticeId = 100
    override fun onCreate() {
        super.onCreate()
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道的方法只会在第一次执行的时候调用
            val channel1 = NotificationChannel("11", "低", NotificationManager.IMPORTANCE_LOW)
            val channel2 = NotificationChannel("12", "高", NotificationManager.IMPORTANCE_HIGH)
            val channel3 = NotificationChannel("13", "默认", NotificationManager.IMPORTANCE_DEFAULT)
            val channel4 = NotificationChannel("14", "最低有的手机不显示", NotificationManager.IMPORTANCE_MIN)
            manager.createNotificationChannel(channel1)
            manager.createNotificationChannel(channel2)
            manager.createNotificationChannel(channel3)
            manager.createNotificationChannel(channel4)
        }
        //如果API大于18，需要弹出一个可见通知
        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, "12")
        } else {
            Notification.Builder(this)
        }
        builder.setSmallIcon(R.mipmap.ic_launcher)
        builder.setContentTitle("庖丁解车APP正在运行,请勿关闭此通知")
        //事件
        val intentClick = Intent(this, MyBroadcastReceiver::class.java)
        intentClick.action = MyConstants.NOTIFICATION_CLICKED
        intentClick.putExtra("CODE", 10)
        intentClick.putExtra("MESSAGE", "消息")
        val pendingIntentClick = PendingIntent.getBroadcast(this, 0, intentClick, PendingIntent.FLAG_ONE_SHOT)
        builder.setContentIntent(pendingIntentClick)
        //点击后自动取消
        builder.setAutoCancel(false)
        startForeground(noticeId, builder.build())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        // 如果Service被杀死，干掉通知
        val mManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        mManager.cancel(noticeId)
        MyLog.d("DaemonService---->onDestroy，前台service被杀死")
        // 重启自己
        val intent = Intent(applicationContext, ResidentService::class.java)
        startService(intent)
    }
}
